package cn.edu.whu.forecast.util;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

public class CopyUtil {
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T target = null;
        try {
            target = clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            return null;
        }
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     * @Author Wang Lang
     * @Description 拷贝列表
     * @Date 2021/11/22 10:45
     * @Param     source 原数据
     * @Param    clazz 目标对象
     * @Return java.util.List<T>
     *  使用示例：{@code
     *     public Map<String, Object> queryReservoirStationAndHydrologyStation() {
     *         Map<String, Object> res = new HashMap<>();
     *         //查询水库站
     *         List<StationReservoir> stationReservoirs = reservoirMapper.selectList();
     *         //查询水文站
     *         List<StationHydrology> stationHydrologies = hydrologyMapper.selectList();
     *         // 该实例中使用方法将List<StationReservoir>转变为List<ReservoirResponseVo>
     *         List<ReservoirResponseVo> reservoirVo = CopyUtil.copyList(stationReservoirs, ReservoirResponseVo.class);
     *         List<HydrologyResponseVo> hydrologyVo = CopyUtil.copyList(stationHydrologies, HydrologyResponseVo.class);
     *         res.put("ReservoirList", reservoirVo);
     *         res.put("HydrologyList", hydrologyVo);
     *         return res;
     *     }
     * }
     */
    public static <T,S> List<T> copyList(List<S> source, Class<T> clazz) {
        return source.stream().map(t -> copy(t, clazz)).collect(Collectors.toList());
    }
}
